package com.ctshk.rpc.order.custom.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.order.custom.constant.Constants;
import com.ctshk.rpc.order.custom.dto.order.CustomOrderDiscountListDTO;
import com.ctshk.rpc.order.custom.entity.*;
import com.ctshk.rpc.order.custom.mapper.*;
import com.ctshk.rpc.order.custom.req.order.*;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderDiscountService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 折扣记录 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-02-22
 */
@DubboService
public class CustomizedOrderDiscountServiceImpl extends ServiceImpl<CustomizedOrderDiscountMapper, CustomizedOrderDiscount> implements ICustomizedOrderDiscountService {

    @Autowired
    private CustomizedOrderDiscountMapper orderDiscountMapper;
    @Autowired
    private CustomizedOrderTouristInfoMapper orderTouristInfoMapper;
    @Autowired
    private CustomizedOrderMapper orderMapper;
    @Autowired
    private CustomizedOrderCollectionMapper orderCollectionMapper;
    @Autowired
    private CustomizedOrderAmountStatisticsMapper orderAmountStatisticsMapper;
    @Autowired
    private CustomizedOrderTouristOtherFeeMapper orderTouristOtherFeeMapper;

    @DubboReference
    private ISysUserService sysUserService;
    //审批服务
    @DubboReference
    private ISysApprovalService sysApprovalService;


    /**
     * 折扣记录列表
     *
     * @param req
     * @return
     */
    @Override
    public PageResponse<CustomOrderDiscountListDTO> list(CustomOrderIdReq req) {
        IPage<CustomOrderIdReq> page = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<CustomOrderDiscountListDTO> pageResult = orderDiscountMapper.selectListBySelective(page, req);
        for (CustomOrderDiscountListDTO record : pageResult.getRecords()) {
            UserDTO crateUser = sysUserService.queryCacheUser(record.getCreateId());
            if (crateUser != null){
                record.setCreateName(crateUser.getCnSurname() + crateUser.getCnName());
                record.setCreateDept(crateUser.getDept());
            }
        }
        PageResponse<CustomOrderDiscountListDTO> response = new PageResponse<>(pageResult.getRecords(),
                pageResult.getCurrent() == 1,
                pageResult.getTotal() <= (pageResult.getCurrent() * pageResult.getSize()),
                pageResult.getTotal(), pageResult.getCurrent(),
                pageResult.getSize());
        return response;
    }

    /**
     * 使用折扣
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(CustomOrderDiscountAddReq req) {
        //获取旅客信息
        QueryWrapper<CustomizedOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getOrderId, req.getOrderId());
        queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getId, req.getTouristId());
        queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getIsDeleted, 0);
        CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectOne(queryWrapper2);
        if (touristInfo == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
        }
        //该用户是否申请过折扣
        CustomizedOrderDiscount orderDiscount = orderDiscountMapper.queryByTourist(req.getOrderId(),req.getTouristId());
        if (orderDiscount != null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4010);
        }
        orderDiscount = EntityUtil.copy(req, CustomizedOrderDiscount.class);
        orderDiscount.setId(IdWorker.getId());
        orderDiscount.setCheckStatus(2);
        LocalDateTime now = LocalDateTime.now();
        orderDiscount.setGmtCreate(now);
        orderDiscount.setCreateId(req.getUserId());
        orderDiscount.setIsDeleted(0);
        //新增折扣记录
        orderDiscount.setBeforeAmount(touristInfo.getTotalReceivables());
        boolean save = save(orderDiscount);
        if (!save){
            throw new BusinessException(SystemError.SYS_437);
        }
        //发起审批流程
        Long approvalId = startApproval(orderDiscount.getId(),req.getOrderId(), req.getUserId());
        orderDiscount.setApprovalId(approvalId);
        boolean update = updateById(orderDiscount);
        if (!update){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(orderDiscount.getId());
    }

    /**
     * 发起审批流程
     * @param id
     * @param userId
     */
    private Long startApproval(Long id,Long orderId, Long userId) {
        Map<String, Object> extendParams = new HashMap<>();
        extendParams.put("id", id);
        try{
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode(),
                    SysApprovalType.DISCOUNT_OUTCUSTOM.getCode(), orderId,
                    userId, null, JSON.toJSONString(extendParams));
            System.out.println("审批结果 =====>>> "+approvalResult.toString());
            if (!approvalResult.isSuccess()) {
                throw new BusinessException(SystemError.CUSTOM_ORDER_4044);
            }
            return approvalResult.getData().getApprovalId();
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_422);
        }
    }

    /**
     * 业务审批
     * @param approvalId    审批id(必填)
     * @param userId        审批人id(必填)
     * @param status        状态-ApprovalStatus枚举code 0 撤回 3 审批不通过 4 审批通过(必填)
     * @param comments      通过或拒绝评论说明(非必填)
     * @return
     */
    private Boolean checkApproval(Long approvalId, Integer status, Long userId,String comments){
        Result<ApprovalCheckDTO> result = sysApprovalService.check(approvalId, userId, status, comments);
        if (result != null && result.isSuccess()){
            return result.getData().getIsFinish();
        }
        return false;
    }


    /**
     * 编辑折扣
     *
     * @param req
     * @return
     */
    @Override
    public Result edit(CustomOrderDiscountEditReq req) {
        //获取折扣记录
        QueryWrapper<CustomizedOrderDiscount> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(CustomizedOrderDiscount::getId, req.getId());
        CustomizedOrderDiscount dbDiscount = orderDiscountMapper.selectOne(queryWrapper1);
        if(dbDiscount == null || !Objects.equals(dbDiscount.getCheckStatus(), 4)) {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4011);
        }
        //更新折扣记录
        CustomizedOrderDiscount orderDiscount = EntityUtil.copy(req, CustomizedOrderDiscount.class);
        orderDiscount.setCheckStatus(2);
        LocalDateTime now = LocalDateTime.now();
        orderDiscount.setGmtModified(now);
        orderDiscount.setModifiedId(req.getUserId());
        orderDiscount.setIsDeleted(0);
        //旅客信息
        QueryWrapper<CustomizedOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getOrderId, req.getOrderId());
        queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getId, req.getTouristId());
        queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getIsDeleted, 0);
        CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectOne(queryWrapper2);
        orderDiscount.setBeforeAmount(touristInfo.getTotalReceivables());
        boolean b = updateById(orderDiscount);
        if (!b){
            throw new BusinessException(SystemError.SYS_437);
        }
        //发起审批流程
        Long approvalId = startApproval(orderDiscount.getId(),req.getOrderId(),req.getUserId());
        orderDiscount.setApprovalId(approvalId);
        boolean update = updateById(orderDiscount);
        if (!update){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(orderDiscount.getId());
    }

    /**
     * 删除折扣
     *
     * @param req
     * @return
     */
    @Override
    public Result delete(CustomOrderDiscountIdReq req) {
        CustomizedOrderDiscount orderDiscount = orderDiscountMapper.selectById(req.getId());
        if (orderDiscount == null || Objects.equals(orderDiscount.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4012);
        }
        if (orderDiscount.getCheckStatus().intValue() != NumberConstant.FOUR.getValue()){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4013);
        }
        orderDiscount.setIsDeleted(1);
        orderDiscount.setModifiedId(req.getUserId());
        orderDiscount.setGmtModified(LocalDateTime.now());
        int del = orderDiscountMapper.updateById(orderDiscount);
        if (del <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success();
    }

    /**
     * 提交審批
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result approval(CustomOrderDiscountAddReq req) {
        CustomizedOrder order = orderMapper.selectById(req.getOrderId());
        if (order == null || Objects.equals(order.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        //该用户是否有申请折扣
        QueryWrapper<CustomizedOrderDiscount> discountWrapper = new QueryWrapper<>();
        discountWrapper.eq("tourist_id",req.getTouristId());
        discountWrapper.eq("order_id",req.getOrderId());
        discountWrapper.eq("is_deleted",0);
        discountWrapper.eq("check_status",2);
        discountWrapper.or();
        discountWrapper.eq("check_status",3);
        CustomizedOrderDiscount discount = orderDiscountMapper.selectOne(discountWrapper);
        if (discount != null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4010);
        }
        //新增折扣记录
        discount = EntityUtil.copy(req,CustomizedOrderDiscount.class);
        discount.setId(SnowflakeIdWorker.nextId());
        discount.setCheckStatus(2);
        discount.setCreateId(req.getUserId());
        discount.setIsDeleted(0);
        int insert = orderDiscountMapper.insert(discount);
        if (insert <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(discount.getId());
    }

    /**
     * 清空订单折扣记录
     *
     * @param orderId
     * @param userId
     * @return
     */
    @Override
    public boolean cleanByOrder(Long orderId,Long userId) {
        //查询订单折扣记录
        QueryWrapper<CustomizedOrderDiscount> discountQueryWrapper = new QueryWrapper<>();
        discountQueryWrapper.eq("order_id",orderId);
        discountQueryWrapper.eq("is_deleted",0);
        List<CustomizedOrderDiscount> discountList = orderDiscountMapper.selectList(discountQueryWrapper);
        if (discountList != null && discountList.size() > 0){
            discountList.forEach(discount -> {
                discount.setModifiedId(userId);
                discount.setIsDeleted(1);
            });
            //批量修改
            return updateBatchById(discountList);
        }
        return true;
    }

    /**
     * 查询旅客折扣金额
     *
     * @param orderId
     * @param touristId
     * @return
     */
    @Override
    public BigDecimal sumAmountByTourist(Long orderId, Long touristId) {
        return orderDiscountMapper.sumAmountByTourist(orderId,touristId);
    }

    /**
     * 清空旅客订单折扣记录
     *
     * @param orderId
     * @param touristId
     * @param userId
     * @return
     */
    @Override
    public boolean cleanByTourist(Long orderId, Long touristId, Long userId) {
        //查询订单折扣记录
        QueryWrapper<CustomizedOrderDiscount> discountQueryWrapper = new QueryWrapper<>();
        discountQueryWrapper.eq("order_id",orderId);
        discountQueryWrapper.eq("tourist_id",touristId);
        discountQueryWrapper.eq("is_deleted",0);
        List<CustomizedOrderDiscount> discountList = orderDiscountMapper.selectList(discountQueryWrapper);
        if (discountList != null && discountList.size() > 0){
            discountList.forEach(discount -> {
                discount.setModifiedId(userId);
                discount.setIsDeleted(1);
            });
            //批量修改
            return updateBatchById(discountList);
        }
        return true;
    }

    /**
     * 審批通过
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result passApproval(CustomOrderDiscountApprovalReq req) {
        QueryWrapper<CustomizedOrderDiscount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("approval_id",req.getApprovalId());
        queryWrapper.eq("is_deleted",0);
        CustomizedOrderDiscount discount = orderDiscountMapper.selectOne(queryWrapper);
        if(discount == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4012);
        }
        if (discount.getCheckStatus().intValue() != NumberConstant.TWO.getValue()){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4035);
        }
        //该用户是否有申请通过的折扣
        QueryWrapper<CustomizedOrderDiscount> discountQueryWrapper = new QueryWrapper<>();
        discountQueryWrapper.eq("order_id",discount.getOrderId());
        discountQueryWrapper.eq("tourist_id",discount.getTouristId());
        discountQueryWrapper.eq("check_status",3);
        discountQueryWrapper.eq("is_deleted",0);
        CustomizedOrderDiscount orderDiscount = orderDiscountMapper.selectOne(discountQueryWrapper);
        if (orderDiscount != null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4010);
        }
        //更新折扣状态
        discount.setCheckStatus(req.getApprovalStatus());
        discount.setModifiedId(req.getUserId());
        int update = orderDiscountMapper.updateById(discount);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        if (Objects.equals(req.getApprovalStatus(),3)){
            //审批通过
            /**
             * 更新金额统计
             */
            //旅客信息
            CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(discount.getTouristId());
            if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue())){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
            }
            //订单统计
            QueryWrapper<CustomizedOrderAmountStatistics> statisticsQueryWrapper = new QueryWrapper<>();
            statisticsQueryWrapper.lambda().eq(CustomizedOrderAmountStatistics::getOrderId, discount.getOrderId());
            CustomizedOrderAmountStatistics statistics = orderAmountStatisticsMapper.selectOne(statisticsQueryWrapper);
            if (statistics == null){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
            }
            //更新旅客统计
            touristInfo.setTotalReceivables(touristInfo.getTotalReceivables().subtract(discount.getDiscountAmount()));
            touristInfo.setRemainingReceivables(touristInfo.getRemainingReceivables().subtract(discount.getDiscountAmount()));
            touristInfo.setOtherAmount(touristInfo.getOtherAmount().subtract(discount.getDiscountAmount()));
            touristInfo.setModifiedId(req.getUserId());
            int update1 = orderTouristInfoMapper.updateById(touristInfo);
            //更新订单统计
            statistics.setOtherAmount(statistics.getOtherAmount().subtract(discount.getDiscountAmount()));
            statistics.setTotalReceivables(statistics.getTotalReceivables().subtract(discount.getDiscountAmount()));
            statistics.setRemainingReceivables(statistics.getRemainingReceivables().subtract(discount.getDiscountAmount()));
            int update2 = orderAmountStatisticsMapper.updateById(statistics);
            //新增其他费用
            CustomizedOrderTouristOtherFee otherFee = new CustomizedOrderTouristOtherFee();
            otherFee.setId(SnowflakeIdWorker.nextId());
            otherFee.setFeeType(2);
            otherFee.setFeeName("折扣");
            otherFee.setOrderId(discount.getOrderId());
            otherFee.setTouristId(discount.getTouristId());
            otherFee.setRelationId(discount.getId());
            otherFee.setAmount(discount.getDiscountAmount());
            otherFee.setGmtCreate(LocalDateTime.now());
            otherFee.setCreateId(req.getUserId());
            otherFee.setIsDeleted(0);
            int insert = orderTouristOtherFeeMapper.insert(otherFee);
            if (update1 <= 0 || update2 <= 0 || insert <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //业务审批
        Result<ApprovalCheckDTO> result = sysApprovalService.check(req.getApprovalId(), req.getUserId(),
                req.getApprovalStatus(), req.getRemark());
        if (!result.isSuccess() || result.getData() == null || !result.getData().getIsFinish()) {
            throw new BusinessException(SystemError.SYS_422);
        }
        return Result.success(discount.getId());
    }

    /**
     * 撤回
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result withdraw(CustomOrderDiscountIdReq req) {
        //查询折扣记录
        QueryWrapper<CustomizedOrderDiscount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("approval_id",req.getId());
        queryWrapper.eq("is_deleted",0);
        CustomizedOrderDiscount discount = orderDiscountMapper.selectOne(queryWrapper);
        if (discount == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4012);
        }
        //操作权限
        if (!Objects.equals(req.getUserId(),discount.getCreateId())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4045);
        }
        //审批中状态才能撤回
        if (!Objects.equals(discount.getCheckStatus(),NumberConstant.TWO.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4046);
        }
        //修改
        discount.setIsDeleted(1);
        discount.setModifiedId(req.getUserId());
        boolean bl = updateById(discount);
        if (!bl){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(discount.getId());
    }

}
